package com.src.xyzk_personal.Service;


import android.app.Service;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.src.xyzk_personal.EOL.DbAdapter;
import com.src.xyzk_personal.EolNewFunctionActivity;
import com.src.xyzk_personal.MainActivity;
import com.src.xyzk_personal.UpApp.UpdateAppService;
import com.src.xyzk_personal.config.Common;
import com.src.xyzk_personal.config.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class UpdateEolService extends Service {

    private UpdateAppService.ThreadUpdate m_thread = null;

    private boolean m_threadstatus = false;
    private boolean web_status = false;

    private final Timer UpdateTimer = new Timer();

    private Timer StatusTimer = new Timer();

    private TimerTask UpdateTask;

    private TimerTask StatusTask;

    Handler StatusHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //启动上送终端状态线程
//            StartStatusDiagnose();
        }
    };


    //获取软件版本号
    private String getVersionName() {
        String versionName = "";
        try {
            versionName = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(e);
        }
        return versionName;
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 首次创建服务时，系统将调用此方法来执行一次性设置程序（在调用 onStartCommand() 或 onBind() 之前）。
     * 如果服务已在运行，则不会调用此方法。该方法只被调用一次
     */
    @Override
    public void onCreate() {
        super.onCreate();
    }


    /**
     * 每次通过startService()方法启动Service时都会被回调。
     *
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        //上送设备是否在线的定时器任务
        StatusTask = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                StatusHandler.sendMessage(message);
            }
        };
        StatusTimer.schedule(StatusTask, 0, 300000);//五分钟进行一次 5*60*1000


        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 服务销毁时的回调
     */
    @Override
    public void onDestroy() {
        System.out.println("onDestroy invoke");
        //定时任务销毁
        UpdateTimer.cancel();
        StatusTimer.cancel();

        super.onDestroy();
    }


    /**
     * 上传修改终端状态线程
     */

    public void StartStatusDiagnose() {
        ThreadStatus threadStatus = new ThreadStatus();
        m_threadstatus = true;
        threadStatus.start();
    }

    public class ThreadStatus extends Thread {

        @Override
        public void run() {
            //获取ip地址
            String ip = getWifiApIpAddress();
            //拼接json
            JSONObject json = new JSONObject();
            try {
                json.put("terminalSerial", Common.BoxName);  // 序列号
                json.put("terminalIp", ip);
                json.put("terminalVersions", getVersionName());
                json.put("terminalStation", Common.cartype.station); //工位号
                json.put("terminalContent", "");//预留字段
            } catch (JSONException e) {
                e.printStackTrace();
            }
            for (int k = 0; k < 3; k++) {
                String res = HttpRequest.sendPut(Common.web_API_AppStatus, json.toString());
                System.out.println(res);
                if (res.indexOf("200") > 0) {
                    web_status = true;
                    break;
                } else {
                    web_status = false;
                }
            }
            if (web_status) {
                try {
                    // 网络终端状态正常，进行数据上传操作
                    DbAdapter db = new DbAdapter(Common.context);
                    //---------------------第一步存主数据库---------------------
                    db.open();
                    List selectmain = db.queryMainTableUnupdate();  //查询主表未上传的数据
                    Map map = new HashMap();
                    for (int i = 0; i < selectmain.size(); i++) {
                        map = (Map) selectmain.get(i);
                        //  查询子表数据
                        String m_vin = (String) map.get(DbAdapter.TableMain.vin);
                        int testnum = Integer.valueOf((String) map.get(DbAdapter.TableMain.testnum));
                        int id = Integer.valueOf((String) map.get(DbAdapter.TableMain.ID));
                        List sublist = db.querysubdataforvin(m_vin, testnum);
                        // 上传数据
//                        SendWebData(map, sublist, id, db);
                        if (Common.updata_isok == true) {
                            db.updatemaintable(id);
                        }
                    }
                    db.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //封装 上传数据的方法
    private void SendWebData(Map mainmap, List sublist, int id, DbAdapter db) {
        //上传web服务器
        JSONObject jsonmain = new JSONObject();
        try {
            jsonmain.put("resultVin", mainmap.get(DbAdapter.TableMain.vin));
            jsonmain.put("resultCar", mainmap.get(DbAdapter.TableMain.car));
            jsonmain.put("resultCartype", mainmap.get(DbAdapter.TableMain.cartype));
            jsonmain.put("resultStation", mainmap.get(DbAdapter.TableMain.station));
            jsonmain.put("resultCarname", mainmap.get(DbAdapter.TableMain.carname));
            jsonmain.put("resultCardate", mainmap.get(DbAdapter.TableMain.timestart));
            jsonmain.put("resultCartime", mainmap.get(DbAdapter.TableMain.timeend));
            jsonmain.put("resultDevice", mainmap.get(DbAdapter.TableMain.device));
            String station = mainmap.get(DbAdapter.TableMain.station).toString();
            if (station.indexOf("-") > 0) {
                jsonmain.put("resultPrintnum", "99");
            } else jsonmain.put("resultPrintnum", Common.Printnum);
            jsonmain.put("resultTestnum", mainmap.get(DbAdapter.TableMain.testnum));
            jsonmain.put("resultResult", mainmap.get(DbAdapter.TableMain.result));
            jsonmain.put("resultPrint", mainmap.get(DbAdapter.TableMain.printdata));
            jsonmain.put("resultPin", mainmap.get(DbAdapter.TableMain.pin));
            jsonmain.put("resultEsk", mainmap.get(DbAdapter.TableMain.esk));
            jsonmain.put("resultAppver", mainmap.get(DbAdapter.TableMain.appversion));
            //未启用
            jsonmain.put("resultColor", mainmap.get(DbAdapter.TableMain.carcolor));
            jsonmain.put("resultUp2mes", "0");
            jsonmain.put("resultUser", "test");

            jsonmain.put("fileName", mainmap.get(DbAdapter.TableMain.logfileName));
            jsonmain.put("resultLog", mainmap.get(DbAdapter.TableMain.logpath));
            JSONArray array = new JSONArray();
            for (int k = 0; k < sublist.size(); k++) {

                Map submap = (Map) sublist.get(k);
                JSONObject jsondetail = new JSONObject();
                jsondetail.put("mVin", mainmap.get(DbAdapter.TableMain.vin));
                jsondetail.put("mTestcode", submap.get(DbAdapter.TableData.testcode));
                jsondetail.put("mContext", submap.get(DbAdapter.TableData.context));
                jsondetail.put("mTestdata", submap.get(DbAdapter.TableData.testdata));
                jsondetail.put("mStand", submap.get(DbAdapter.TableData.testctand));
                jsondetail.put("mResult", submap.get(DbAdapter.TableData.result));
                array.put(k, jsondetail);
            }
            jsonmain.put("tableResultDetails", array);
            Long v_upfileid = (long) 0;
            for (int k = 0; k < 3; k++) {
                String res = HttpRequest.sendPostToMyMes(Common.Web_Result_Add, jsonmain.toString().replace(">", ""));
                if (res.indexOf("200") > 0) //ok
                {
                    Common.updata_isok = true;
                    db.updatemaintable(id);

                    JSONObject resjson = new JSONObject(res);
                    JSONObject son = resjson.getJSONObject("data");
                    if (son != null)
                        v_upfileid = son.getLong("resultId");
                    break;
                } else {
                    Common.updata_isok = false;
                }
            }
            //上传日志文件
            if (v_upfileid > 0) {
                uploadFiles(Common.Web_Result_Uploadfile, (String) mainmap.get(DbAdapter.TableMain.logpath), v_upfileid);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //  上传日志文件

    /**
     * 文件上传线程
     *
     * @param uploadUrl
     * @param filePaths
     * @param id
     */

    public void uploadFiles(String uploadUrl, String filePaths, Long id) {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        String fname = filePaths;
        File tempfile = new File(fname);
        //根据文件的后缀名，获得文件类型
        builder.setType(MultipartBody.FORM)
                .addFormDataPart("resultId", String.valueOf(id))// 其他参数信息
                .addFormDataPart( //给Builder添加上传的文件
                        "files",  //请求的名字
                        tempfile.getName(), //文件的文字，服务器端用来解析的
                        RequestBody.create(MediaType.parse("multipart/form-data"), tempfile)//创建RequestBody，把上传的文件放入
                );
        MultipartBody requestBody = builder.build();
        Request request = new Request.Builder()
                .url(uploadUrl)
                .post(requestBody)
                .build();
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.SECONDS)
                .readTimeout(10000, TimeUnit.SECONDS)
                .writeTimeout(10000, TimeUnit.SECONDS).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                Log.e("TAG", "返回内容===失败>:" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e("TAG", "返回内容===成功>:" + result);
            }
        });
    }

    //获取ip
    public String getWifiApIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                    .hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                if (intf.getName().contains("wlan")) {
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                            .hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()
                                && (inetAddress.getAddress().length == 4)) {
                            Log.d("TAG", inetAddress.getHostAddress());
                            return inetAddress.getHostAddress();
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("TAG", ex.toString());
        }
        return null;
    }
}
